package com.cy4;

import java.util.Arrays;
import java.util.Stack;

/**
 * 自己实现栈
 *
 * @author CY
 * @date 2022/10/13 03:32
 **/
public class MyStack {
    public int[] elem;
    public int usedSize;
    public static final int DEFAULT_SIZE = 10;

    public MyStack() {
        elem = new int[DEFAULT_SIZE];
    }

    public int push(int value) {
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2 * elem.length);
        }
        this.elem[usedSize++] = value;
        return value;
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public int pop() {
        if (isEmpty()) {
            throw new MyStackEmptyException("栈为空！");
        }
        return this.elem[--usedSize];
    }

    public int peek() {
        if (isEmpty()) {
            throw new MyStackEmptyException("栈为空！");
        }
        return this.elem[usedSize - 1];

    }

    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        myStack.push(25);
        myStack.push(152);
        myStack.push(254);
        myStack.push(250);
        System.out.print(myStack.pop() + " ");
        System.out.print(myStack.pop() + " ");
        System.out.print(myStack.pop() + " ");
//        System.out.print(myStack.pop()+" ");
        //这一次，栈为空，抛异常
//        System.out.print(myStack.pop() + " ");
//        System.out.println(myStack.isValid("j"));
        System.out.println(myStack.IsPopOrder());


    }
    public boolean IsPopOrder() {
        int[] pushA=new int[]{2,1,0};
        int[] popA=new int[]{1,2,0};
        Stack<Integer> sk=new Stack<>();
        if(pushA.length==1){
            if(pushA[0]==popA[0]){
                return true;
            }else{
                return false;
            }
        }
        int i=0;
        int j=0;for(i=0;i<pushA.length;i++){
            if(pushA[i]!=popA[j]){
                sk.push(pushA[i]);

            }else{
                sk.pop();
                j++;
                while(!sk.empty()&&j< popA.length&&sk.peek()==popA[j]){
                    sk.pop();
                }
            }
        }
        return sk.empty();
    }

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
                if (stack.empty()) {
                    return false;
                }
                if (((ch == ')') && (stack.peek() == '(')) || ((ch == ']') && (stack.peek() == '[')) || ((ch == '}') && (stack.peek() == '{'))) {
                    if (!stack.empty()) {
                        stack.pop();
                    }

                } else {
                    return false;
                }
            }
        }
        return stack.empty();
    }
}
